package com.mingzhi.blog.controller;

import com.mingzhi.blog.enmus.ResultCodeEnum;
import com.mingzhi.blog.model.Result;
import com.mingzhi.blog.model.UserInfo;
import com.mingzhi.blog.service.UserService;
import com.mingzhi.blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 登录接口
     *
     */
    @RequestMapping("/login")
    public Result login(String userName,String password){
        //先校验
        if (!StringUtils.hasLength(userName) && !StringUtils.hasLength(password)){
            return Result.fail(ResultCodeEnum.PARAM_INVAILD.getCode(),"账号或密码不能为空");
        }
        //再校验账号密码是否正确
        UserInfo userInfo = userService.selectUserByName(userName);
        if (userInfo == null || userInfo.getId() == null){
            return Result.fail(ResultCodeEnum.PARAM_INVAILD.getCode(),"用户不存在");
        }
        if (!password.equals(userInfo.getPassword())){
            return Result.fail(ResultCodeEnum.PARAM_INVAILD.getCode(),"用户名或密码错误");
        }
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id",userInfo.getId());
        cliams.put("name",userInfo.getUserName());
        String token = JwtUtils.getJwt(cliams);
        return Result.success(token);
    }
}
